package JudgeProcess;
import java.io.*;
import java.lang.reflect.*;
import java.net.URL;
import java.net.URLClassLoader;

public class Compile 
{
	protected String personId = null;
	protected String questionId = null;
	protected String source_name = Constant.FORM_PROG_UPLOAD;
	protected String class_name = null;
    public Compile(String personId, String questionId)
    {
    	//assign variables
    	this.personId = personId;
    	this.questionId = questionId;
    	//edit program name according to the file form
    	this.source_name = this.source_name.replace(Constant.LABEL_PERSON, personId);
    	this.source_name = this.source_name.replace(Constant.LABEL_QUSETION, this._003_numFormat(questionId));
    	//set class name
    	this.class_name = this.source_name.substring(0, this.source_name.length() - 5);
    	//start compile
    	if (this._001_compileIt()) 
    	{
    	    System.out.println("Compile  " + this.class_name + "  ok\n");
    	    this._002_runIt();
    	}
    	else
    	{
    	    System.out.println(this.source_name + " is bad.");
    	}
    }
    public boolean _001_compileIt() 
    {
        String [] source = { new String(Constant.DIR_USER_UPLOAD + "/" + this.source_name)};
        ByteArrayOutputStream baos= new ByteArrayOutputStream();
        new sun.tools.javac.Main(baos,source[0]).compile(source); 
        return (baos.toString().indexOf("error")==-1);
    }
    public void _002_runIt() 
    {
    	PrintStream oldOut = System.out;
        PrintStream oldErr = System.err;
        try 
        {
        	PrintStream ps = new PrintStream(new File(Constant.DATA_USER_RESULT));
            System.setOut(ps);
            System.setErr(ps);
	        Class params[] = new Class[] { String[].class };
	        Object paramsObj[] = new Object[] { null };
	        
	        File directory = new File("."); 
	        URL url = new URL("file:/" + Constant.DIR_USER_UPLOAD + "/");
	        URLClassLoader loader = new URLClassLoader(new URL[] { url });
	          
	        Class thisClass = loader.loadClass(this.class_name);
	        Method thisMethod = thisClass.getDeclaredMethod("main", params);
	        thisMethod.invoke(thisClass, paramsObj);
	        
	        System.setOut(oldOut);
            System.setErr(oldErr);
        }
        catch (Exception e) 
        {
            e.printStackTrace();
        }
    }
    public static String _003_numFormat(String num)
	{
		String newStr = num.substring(0);
		int index = 0;
		while(index < Constant.MAX_NO_DIGIT - num.length())
		{
			newStr = "0" + newStr;
			index = index + 1;
		}
		return newStr;
	}
}
